<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="姓名" prop="userName" label-width="40px">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" label-width="40px">
        <el-select
          v-model="queryParams.gender"
          clearable
          size="small"
          style="width: 100px"
        >
          <el-option
            key="0"
            label="男"
            value="0"
          />
          <el-option
            key="1"
            label="女"
            value="1"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['community:member:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['community:member:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['community:member:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['community:member:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="50" />
      <!--      <el-table-column label="用户id" align="center" prop="userId" />-->
      <!--      <el-table-column label="身份证号" align="center" prop="idNumber" />-->
      <el-table-column label="用户名" align="center" prop="userName" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="真实姓名" align="center" prop="realName" />
      <el-table-column label="手机号码" align="center" prop="userPhone" width="120"/>
      <!--      <el-table-column label="现居住地" align="center" prop="userAddress" />-->
      <el-table-column label="性别" :formatter="formatterGender" align="center" prop="gender" width="60"/>
      <el-table-column label="年龄" align="center" prop="age" width="60"/>
      <el-table-column label="党龄" :formatter="formatterPartyDate" align="center" prop="partyDate" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['community:member:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['community:member:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改党员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idNumber">
              <el-input v-model="form.idNumber" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="性别" prop="gender">
              <!--          <el-input v-model="form.gender" placeholder="请输入0男1女2未知" />-->
              <el-select v-model="form.gender"
                         clearable
                         size="small"
                         style="width: 100px">
                <el-option key="0"
                           label="男"
                           value="0" />
                <el-option key="1"
                           label="女"
                           value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="民族" prop="nationality">
              <NationalitySelect :nationV="form.nationality" @nationvalue="nationvalueChange"></NationalitySelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="籍贯" prop="nativeAddress">
              <el-input v-model="form.nativeAddress" placeholder="请输入籍贯" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="form.birthDate"
                clearable
                size="small"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择出生日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入党日期" prop="partyDate">
              <el-date-picker
                v-model="form.partyDate"
                clearable
                size="small"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择入党日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="userPhone">
              <el-input v-model="form.userPhone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="现居住地" prop="userAddress">
              <el-input v-model="form.userAddress" placeholder="请输入现居住地" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注信息" prop="information">
          <el-input v-model="form.information" maxlength="200" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" show-word-limit placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 搜索用户，添加用户为党员对话框 -->
    <el-dialog title="添加党员" :visible.sync="addOpen" width="700px" append-to-body>
      <el-form ref="userForm" :model="userQueryParams" label-width="68px" :inline="true">
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="userQueryParams.userName"
            clearable
            size="mini"
            @keyup.enter.native="handleUserQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="userQueryParams.phonenumber"
            clearable
            size="mini"
            @keyup.enter.native="handleUserQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" circle @click="handleUserQuery" />
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="userList" max-height="250">
        <el-table-column label="用户名称" align="center" prop="userName" />
        <el-table-column label="用户昵称" align="center" prop="nickName" />
        <el-table-column label="部门" align="center" prop="dept.deptName" />
        <el-table-column label="手机号码" align="center" prop="phonenumber" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.ifCpc"
              size="mini"
              type="text"
              style="color: gray"
              disabled
            >已添加</el-button>
            <el-button
              v-else
              v-hasPermi="['community:member:add']"
              size="mini"
              type="text"
              @click="handleAddMember(scope.row, scope.$index)"
            >添加</el-button>

<!--            <el-button-->
<!--              v-if="scope.row.ifCpc===false"-->
<!--              v-hasPermi="['community:member:add']"-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              @click="handleAddMember(scope.row)"-->
<!--            >添加</el-button>-->
<!--            <el-button-->
<!--              v-else-->
<!--              v-hasPermi="['community:member:add']"-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              style="color: gray"-->
<!--              disabled-->
<!--            >已添加</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
        <el-button @click="cancelAdd">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMember, listMemberInfo, ifCpc, getMember, delMember, addMember, updateMember, exportMember } from '@/api/cpc/member'
import { DateToAge } from '@/utils/dateUtils'
import { listUser } from '@/api/system/user'

export default {
  name: 'Member',
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 党员表格数据
      memberList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        idNumber: null,
        userName: null,
        userPhone: null,
        userAddress: null,
        gender: null,
        age: null,
        birthDate: null,
        nationality: null,
        partyDate: null,
        nativeAddress: null,
        information: null,
        creater: null,
        syncTime: null,
        communityId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 添加党员相关变量
      userLoading: false,
      addOpen: false,
      // 用户查询参数
      userQueryParams: {
        userName: null,
        phonenumber: null,
      },
      // 用户检索结果表格数据
      userList: [],
      // 新增成员隐藏表单参数
      userForm: {
        userId: null
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 接收民族选择器改变值 **/
    nationvalueChange(data) {
      this.form.nationality = data
    },
    /** 正确显示表格中的性别 **/
    formatterGender(row, column) {
      if (row.gender === '0') {
        return '男'
      } else if (row.gender === '1') {
        return '女'
      } else {
        return null
      }
    },
    /** 将入党日期转换为党龄 **/
    formatterPartyDate(row, column) {
      if (row.partyDate != null) {
        return DateToAge(row.partyDate) + '年'
      }
      return null
    },
    /** 查询党员列表 */
    getList() {
      this.loading = true
      listMemberInfo(this.queryParams).then(response => {
        // console.log('党员用户信息', response.rows)
        this.memberList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消添加党员
    cancelAdd() {
      this.addOpen = false
      this.userQueryParams = {
        userName: null,
        phonenumber: null,
      }
      this.userList = []
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        idNumber: null,
        userName: null,
        userPhone: null,
        userAddress: null,
        gender: null,
        age: null,
        birthDate: null,
        nationality: null,
        partyDate: null,
        nativeAddress: null,
        information: null,
        creater: null,
        syncTime: null,
        communityId: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 搜索用户按钮操作 */
    handleUserQuery() {
      this.userList = []
      this.userLoading = true
      // this.userQueryParams.communityId = this.currentCommunityID;
      listUser(this.userQueryParams).then(
        (response) => {
          const tmp = response.rows
          for (let i = 0; i < tmp.length; i++) {
            ifCpc(tmp[i].userId).then(ifResponse => {
              tmp[i].ifCpc = ifResponse
              this.userList.push(tmp[i])
            })
          }
          console.log(this.userList)
          this.userLoading = false
        }
      )
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset()
      this.addOpen = true
    },
    /** 添加党员操作 */
    handleAddMember(row, rowIndex) {
      // this.userForm.userId = row.userId
      // addMember(this.userForm).then(response => {
      addMember(row).then(response => {
        this.msgSuccess('添加成功')
        this.userList[rowIndex].ifCpc = true
        this.getList()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMember(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改党员'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.age = DateToAge(this.form.birthDate)
          if (this.form.id != null) {
            updateMember(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            // addMember(this.form).then(response => {
            //   this.msgSuccess('新增成功')
            //   this.open = false
            //   this.getList()
            // })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除该党员', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delMember(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有党员数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportMember(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>
